#!/bin/bash

# iOS 真机部署脚本
# 使用方法: ./deploy_ios.sh [设备名称或ID]

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${GREEN}=====================================${NC}"
echo -e "${GREEN}  iOS 真机部署脚本${NC}"
echo -e "${GREEN}=====================================${NC}"
echo ""

# 1. 检查 Flutter 环境
echo -e "${YELLOW}[1/6] 检查 Flutter 环境...${NC}"
if ! command -v flutter &> /dev/null; then
    echo -e "${RED}错误: 未找到 Flutter 命令，请确保已安装 Flutter${NC}"
    exit 1
fi
flutter --version
echo ""

# 2. 列出可用设备
echo -e "${YELLOW}[2/6] 检查可用设备...${NC}"
flutter devices
echo ""

# 3. 获取目标设备
DEVICE_ID=""
if [ -n "$1" ]; then
    DEVICE_ID="$1"
    echo -e "${GREEN}使用指定设备: $DEVICE_ID${NC}"
else
    # 尝试自动获取第一个 iOS 设备
    DEVICE_ID=$(flutter devices | grep "ios" | grep -v "simulator" | head -n 1 | awk '{print $5}' | tr -d '•')
    if [ -z "$DEVICE_ID" ]; then
        echo -e "${RED}错误: 未找到连接的 iOS 设备${NC}"
        echo -e "${YELLOW}提示: 请连接 iOS 设备或指定设备ID: ./deploy_ios.sh <device-id>${NC}"
        exit 1
    fi
    echo -e "${GREEN}自动选择设备: $DEVICE_ID${NC}"
fi
echo ""

# 4. 清理并获取依赖
echo -e "${YELLOW}[3/6] 清理并获取依赖...${NC}"
flutter clean
flutter pub get
echo ""

# 5. 安装 CocoaPods 依赖
echo -e "${YELLOW}[4/6] 安装 CocoaPods 依赖...${NC}"
cd ios
pod install
cd ..
echo ""

# 6. 构建并部署到真机
echo -e "${YELLOW}[5/6] 构建并部署到真机...${NC}"
echo -e "${GREEN}目标设备: $DEVICE_ID${NC}"
flutter run -d "$DEVICE_ID" --release

# 完成
echo ""
echo -e "${GREEN}=====================================${NC}"
echo -e "${GREEN}  部署完成！${NC}"
echo -e "${GREEN}=====================================${NC}"
